package com.hgw.imsever.netty.task;

import com.google.common.collect.Lists;
import com.hgw.imsever.common.RedisKeyConsts;
import com.hgw.imsever.common.utils.HashingUtils;
import com.hgw.imsever.common.utils.RedisUtil;
import org.apache.commons.lang3.BooleanUtils;

import java.util.List;

/**
 *  用户上线任务
 */
public class UserOnlineTask implements Runnable {

    private String channelId;

    private String userId;

    private RedisUtil redisUtil;

    public UserOnlineTask(String channelId, String userId, RedisUtil redisUtil) {
        this.channelId = channelId;
        this.userId = userId;
        this.redisUtil = redisUtil;
    }

    @Override
    public void run() {

        /**
         *  1.保存用户Id和通道的对应关系
         *  2.位图保存用户的存活状态
         */
        String script = "redis.call('hset',KEYS[1],KEYS[2],ARGV[1])\n" +
                "redis.call('setbit',KEYS[3],KEYS[4],ARGV[2])\n";
        List<String> keys = Lists.newArrayList();
        keys.add(RedisKeyConsts.CHAT_CHANNEL_USER);
        keys.add(channelId);
        keys.add(RedisKeyConsts.USER_ALIVE_STATUS_KEY);
        keys.add(String.valueOf(HashingUtils.hash(userId)));
        List<String> args = Lists.newArrayList();
        args.add(userId);
        args.add(String.valueOf(BooleanUtils.toInteger(true)));
        redisUtil.evalScript(script, keys, args);
    }
}
